<?php


namespace app\admin\controller;


use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class UserController extends CommonController
{

    private static $USER_TABLE="user";
    private static $USER_ROLE_TABLE="user_role";
    private static $SALT_DIY = "lan";


    public function addUser(Request $request)
    {
        $res= $request->param();
        $rule = [
            'account'  => 'require|max:10',
            'info'   => 'require|max:20',
            'password'   => 'require',
            'repassword'   => 'require',
            'role_id'   => 'require',
        ];
        $message  = [
            'account.require' => '账号名称必填',
            'account.max' => '账号名称最多10个字符',
            'info.require'=> '账号简介必填',
            'info.max' => '账号简介最多20个字符',
            'role_id.require' => '请选择角色',
            'password.require' => '密码必填',
            'repassword.require' => '重复密码必填',
        ];
        $validate = Validate::make($rule,$message);
        $result = $validate->check($res);
        if(!$result) {
          return  returnFail($validate->getError());
        }
        if(!$request->param('ava_url')){
            $res['ava_url']='http://dns.shmilyi.cn/1622683110.jpeg';
        }
        $is_exit=Db::table(self::$USER_TABLE)
            ->where('delete_flag','=',0)
            ->where('account','=',$res['account'])
            ->find();
        if ($is_exit){
            return returnFail('账号重复');
        }
        if ($res['password']!=$res['repassword']){
            return returnFail('两次密码不一致');
        }
        $salt=$this->GetRandStr(5);
        $password=self::$SALT_DIY.$res['password'].$salt;
        //拿到前端传的加密密码 进行二次加密
        $passHash = password_hash($password, PASSWORD_DEFAULT);
        $insert_data=['account'=>$res['account'],'info'=>$res['info'],'ava_url'=>$res['ava_url'],'password'=>$passHash,'salt'=>$salt,'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date('Y-m-d H:i:s',time())];
        try {
            Db::startTrans();
            $user_id=Db::table(self::$USER_TABLE)->insertGetId($insert_data);
            DB::table(self::$USER_ROLE_TABLE)->insert(['user_id'=>$user_id,'role_id'=>$res['role_id'],'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date('Y-m-d H:i:s',time())]);
            DB::commit();
            return returnSuccess([],'添加成功');
        }catch (Exception $e){
            Db::rollback();
            return returnFail($e->getMessage());
        }
    }

    public function getUserList(Request $request)
    {
        $page=$request->get('page')?:self::$Page;
        $limit=$request->get('limit')?:self::$Limit;
       $res= Db::table(self::$USER_TABLE)
            ->alias('a')
            ->join('user_role b','a.id = b.user_id')
            ->join('role c','c.id = b.role_id')
            ->where('a.delete_flag','=',0)
            ->where('b.delete_flag','=',0)
            ->where('c.delete_flag','=',0)
            ->where(function ($query) use($request){
                if ($request->get('search_name')!=null||!empty($request->get('search_name'))){
                    $query->where('a.account','like','%'.$request->get('search_name').'%');
                }
                if ($request->get('search_role')!=null||!empty($request->get('search_role'))){
                    $query->where('c.name','like','%'.$request->get('search_role').'%');
                }
            })
            ->field('a.id,a.account,a.status,a.login_time,c.id as role_id,c.name as role_name,a.info,a.ava_url')
            ->limit($limit)
            ->page($page)
            ->select();
        $total= Db::table(self::$USER_TABLE)
            ->alias('a')
            ->join('user_role b','a.id = b.user_id')
            ->join('role c','c.id = b.role_id')
            ->where('a.delete_flag','=',0)
            ->where('b.delete_flag','=',0)
            ->where('c.delete_flag','=',0)
            ->count();
        $fenye=['limit'=>$limit,'page'=>$page,'total'=>$total];
        $data=['res'=>$res,'fenye'=>$fenye];
        return returnSuccess($data,'success');
    }

    public function CheckUserStatus(Request $request)
    {
        if (!$request->get('id')){
            return returnFail('缺少参数');
        }
        $status=$request->get('status')==1?:0;
        try {
            Db::table(self::$USER_TABLE)->where('id','=',$request->get('id'))->update(['status'=>$status,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            return returnSuccess([],'更新成功');
        }catch (Exception $e){
            return returnFail($e->getMessage());
        }
    }

    public function updateUser(Request $request)
    {
        $res= $request->param();
        $rule = [
            'account'  => 'require|max:10',
            'info'   => 'require|max:20',
            'role_id'   => 'require',
            'id'=>'require'
        ];
        $message  = [
            'account.require' => '账号名称必填',
            'account.max' => '账号名称最多10个字符',
            'info.require'=> '账号简介必填',
            'info.max' => '账号简介最多20个字符',
            'role_id.require' => '请选择角色',
            'id.require' => '参数错误',
        ];
        $validate = Validate::make($rule,$message);
        $result = $validate->check($res);
        if(!$result) {
            return returnFail($validate->getError());
        }
        if(!$request->param('ava_url')){
            $res['ava_url']='http://dns.shmilyi.cn/1622683110.jpeg';
        }
        $is_exit=Db::table(self::$USER_TABLE)
            ->where('delete_flag','=',0)
            ->where('account','=',$res['account'])
            ->where('id','<>',$res['id'])
            ->find();
        if ($is_exit){
            return returnFail('账号重复');
        }

        //判断是否需要更换密码
        if ((isset($res['password'])&&isset($res['repassword']))||(!empty($res['password'])&&!empty($res['repassword']))) {
            $salt=$this->GetRandStr(5);
            $password=self::$SALT_DIY.$res['password'].$salt;
            $passHash = password_hash($password, PASSWORD_DEFAULT);
            $update_data=['account'=>$res['account'],'info'=>$res['info'],'ava_url'=>$res['ava_url'],'password'=>$passHash,'salt'=>$salt,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())];
        }else{
            $update_data=['account'=>$res['account'],'info'=>$res['info'],'ava_url'=>$res['ava_url'],'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())];
        }
        try {
            Db::startTrans();
            Db::table(self::$USER_TABLE)->where('id','=',$res['id'])->update($update_data);
            Db::table(self::$USER_ROLE_TABLE)->where('user_id','=',$res['id'])->update(['role_id'=>$res['role_id'],'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            Db::commit();
            return returnSuccess([],'修改成功');
        }catch (Exception $e){
            Db::rollback();
            return returnFail($e->getMessage());
        }
    }

    public function deleteUser(Request $request){
        $id=$request->post('id');
        if (!$id){
            return returnFail('参数错误');
        }
        try {
            Db::startTrans();
            Db::table(self::$USER_TABLE)->where('id','=',$id)->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            Db::table(self::$USER_ROLE_TABLE)->where('user_id','=',$id)->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            Db::commit();
            return returnSuccess([],'删除成功');
        }catch (Exception $e){
            Db::rollback();
            return returnFail($e->getMessage());
        }
    }




}